﻿namespace Tencent
{
    using System;
    using System.IO;
    using System.Net;
    using System.Security.Cryptography;
    using System.Text;

    internal class Cryptography
    {
        private static byte[] AES_decrypt(string Input, byte[] Iv, byte[] Key)
        {
            RijndaelManaged aes = new RijndaelManaged();
            aes.KeySize = 0x100;
            aes.BlockSize = 0x80;
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.None;
            aes.Key = Key;
            aes.IV = Iv;
            ICryptoTransform decrypt = aes.CreateDecryptor(aes.Key, aes.IV);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, decrypt, CryptoStreamMode.Write))
                {
                    byte[] xXml = Convert.FromBase64String(Input);
                    byte[] msg = new byte[(xXml.Length + 0x20) - (xXml.Length % 0x20)];
                    Array.Copy(xXml, msg, xXml.Length);
                    cs.Write(xXml, 0, xXml.Length);
                }
                return decode2(ms.ToArray());
            }
        }

        public static string AES_decrypt(string Input, string EncodingAESKey, ref string appid)
        {
            byte[] Key = Convert.FromBase64String(EncodingAESKey + "=");
            byte[] Iv = new byte[0x10];
            Array.Copy(Key, Iv, 0x10);
            byte[] btmpMsg = AES_decrypt(Input, Iv, Key);
            int len = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(btmpMsg, 0x10));
            byte[] bMsg = new byte[len];
            byte[] bAppid = new byte[(btmpMsg.Length - 20) - len];
            Array.Copy(btmpMsg, 20, bMsg, 0, len);
            Array.Copy(btmpMsg, 20 + len, bAppid, 0, (btmpMsg.Length - 20) - len);
            string oriMsg = Encoding.UTF8.GetString(bMsg);
            appid = Encoding.UTF8.GetString(bAppid);
            return oriMsg;
        }

        private static string AES_encrypt(string Input, byte[] Iv, byte[] Key)
        {
            RijndaelManaged aes = new RijndaelManaged();
            aes.KeySize = 0x100;
            aes.BlockSize = 0x80;
            aes.Padding = PaddingMode.PKCS7;
            aes.Mode = CipherMode.CBC;
            aes.Key = Key;
            aes.IV = Iv;
            ICryptoTransform encrypt = aes.CreateEncryptor(aes.Key, aes.IV);
            byte[] xBuff = null;
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write))
                {
                    byte[] xXml = Encoding.UTF8.GetBytes(Input);
                    cs.Write(xXml, 0, xXml.Length);
                }
                xBuff = ms.ToArray();
            }
            return Convert.ToBase64String(xBuff);
        }

        public static string AES_encrypt(string Input, string EncodingAESKey, string appid)
        {
            byte[] Key = Convert.FromBase64String(EncodingAESKey + "=");
            byte[] Iv = new byte[0x10];
            Array.Copy(Key, Iv, 0x10);
            string Randcode = CreateRandCode(0x10);
            byte[] bRand = Encoding.UTF8.GetBytes(Randcode);
            byte[] bAppid = Encoding.UTF8.GetBytes(appid);
            byte[] btmpMsg = Encoding.UTF8.GetBytes(Input);
            byte[] bMsgLen = BitConverter.GetBytes(HostToNetworkOrder(btmpMsg.Length));
            byte[] bMsg = new byte[((bRand.Length + bMsgLen.Length) + bAppid.Length) + btmpMsg.Length];
            Array.Copy(bRand, bMsg, bRand.Length);
            Array.Copy(bMsgLen, 0, bMsg, bRand.Length, bMsgLen.Length);
            Array.Copy(btmpMsg, 0, bMsg, bRand.Length + bMsgLen.Length, btmpMsg.Length);
            Array.Copy(bAppid, 0, bMsg, (bRand.Length + bMsgLen.Length) + btmpMsg.Length, bAppid.Length);
            return AES_encrypt(bMsg, Iv, Key);
        }

        private static string AES_encrypt(byte[] Input, byte[] Iv, byte[] Key)
        {
            RijndaelManaged aes = new RijndaelManaged();
            aes.KeySize = 0x100;
            aes.BlockSize = 0x80;
            aes.Padding = PaddingMode.None;
            aes.Mode = CipherMode.CBC;
            aes.Key = Key;
            aes.IV = Iv;
            ICryptoTransform encrypt = aes.CreateEncryptor(aes.Key, aes.IV);
            byte[] xBuff = null;
            byte[] msg = new byte[(Input.Length + 0x20) - (Input.Length % 0x20)];
            Array.Copy(Input, msg, Input.Length);
            byte[] pad = KCS7Encoder(Input.Length);
            Array.Copy(pad, 0, msg, Input.Length, pad.Length);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write))
                {
                    cs.Write(msg, 0, msg.Length);
                }
                xBuff = ms.ToArray();
            }
            return Convert.ToBase64String(xBuff);
        }

        private static char chr(int a)
        {
            byte target = (byte) (a & 0xff);
            return (char) target;
        }

        private static string CreateRandCode(int codeLen)
        {
            string codeSerial = "2,3,4,5,6,7,a,c,d,e,f,h,i,j,k,m,n,p,r,s,t,A,C,D,E,F,G,H,J,K,M,N,P,Q,R,S,U,V,W,X,Y,Z";
            if (codeLen == 0)
            {
                codeLen = 0x10;
            }
            string[] arr = codeSerial.Split(new char[] { ',' });
            string code = "";
            int randValue = -1;
            Random rand = new Random((int) DateTime.Now.Ticks);
            for (int i = 0; i < codeLen; i++)
            {
                randValue = rand.Next(0, arr.Length - 1);
                code = code + arr[randValue];
            }
            return code;
        }

        private static byte[] decode2(byte[] decrypted)
        {
            int pad = decrypted[decrypted.Length - 1];
            if ((pad < 1) || (pad > 0x20))
            {
                pad = 0;
            }
            byte[] res = new byte[decrypted.Length - pad];
            Array.Copy(decrypted, 0, res, 0, decrypted.Length - pad);
            return res;
        }

        public static int HostToNetworkOrder(int inval)
        {
            int outval = 0;
            for (int i = 0; i < 4; i++)
            {
                outval = (outval << 8) + ((inval >> (i * 8)) & 0xff);
            }
            return outval;
        }

        public static uint HostToNetworkOrder(uint inval)
        {
            uint outval = 0;
            for (int i = 0; i < 4; i++)
            {
                outval = (outval << 8) + ((inval >> (i * 8)) & 0xff);
            }
            return outval;
        }

        private static byte[] KCS7Encoder(int text_length)
        {
            int block_size = 0x20;
            int amount_to_pad = block_size - (text_length % block_size);
            if (amount_to_pad == 0)
            {
                amount_to_pad = block_size;
            }
            char pad_chr = chr(amount_to_pad);
            string tmp = "";
            for (int index = 0; index < amount_to_pad; index++)
            {
                tmp = tmp + pad_chr;
            }
            return Encoding.UTF8.GetBytes(tmp);
        }
    }
}

